var md5s = require('./new/md5.js');
var utilBase64 = require('./new/opbase64.js');
var CryptoJS = require('./new/crypot.js');
const app = getApp();
const util = require('./util');
const host = 'https://mmchengren.com/api/';
const hosts = 'https://mmchengren.com/apis/';
// 密钥 16 位
var key = 'shdgfuskasejwwwd';
// 初始向量 initial vector 16 位
var iv = 'shdgfuskasejwwwd';
var keys = CryptoJS.enc.Utf8.parse(key);
iv = CryptoJS.enc.Utf8.parse(iv);

var myDate = new Date();
var str = '';
/**
 * 封装微信的request
 * form: 'application/x-www-form-urlencoded'
 */ // const key = 'sdfkjrjeneeeee33'; //签名验证
function addsanferewr(param) {
	let secretKey =keys;
	let iv =keys;
	let encryptedParams = typeof param === 'string' ? param : JSON.stringify(param)
	let encrypted = CryptoJS.AES.encrypt(encryptedParams, secretKey, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	})
	return encrypted.toString();
  
}
//解密

/** 判断是否是纯字符串还是JSON字符串
 * @param {Object} value
 */
function isStringOrValidJSON(value) {
	try {
		JSON.parse(value);
		return 'JSON';
	} catch (e) {
		if (typeof value === 'string') {
			return 'String';
		}
	}
	return 'Invalid';
}
function decryptAES(params,keyd) {
	keyd=CryptoJS.enc.Utf8.parse(keyd);
	let decrypted = CryptoJS.AES.decrypt(params,keyd, {
		iv: iv,
		mode: CryptoJS.mode.CBC, // 加密模式
		padding: CryptoJS.pad.Pkcs7 // 填充方式
	});
	let decryptedData = decrypted.toString(CryptoJS.enc.Utf8)
	// a.解密的数据为纯字符串则直接return
	// b.解密的数据为JSON后的字符串则 JSON.parse 后返回
	// c.无法解析其类型则返回空数据
	switch (isStringOrValidJSON(decryptedData)) {
		case 'String':
			return decryptedData
			break;
		case 'JSON':
			return JSON.parse(decryptedData)
			break;
		default:
			return ""
			break;
	}
}

function objKeySort(arys) {
    var newkey = Object.keys(arys).sort();
    var newObj = {};
    for (var i = 0; i < newkey.length; i++) {
        newObj[newkey[i]] = arys[newkey[i]];
    }
    return newObj;
}
function app_keyd(string) {
    var app_key = md5s.md5(string);
    app_key = app_key.substring(0, 10);
    app_key = md5s.md5(app_key);
    return app_key;
}
function signature(data) {
    var dk = key;
    var n = null;
    var d = {};
    var str = '';
    var s = '';
    n = Object.keys(data).sort();
    for (var i in n) {
        d[n[i]] = data[n[i]];
    }
    for (var k in d) {
        if (d[k] === '') {
            continue;
        }
        if (str != '') {
            str += '&';
        }
        str += k + '=' + encodeURI(d[k]);
    }
    str += '&key=' + dk;
    s = md5s.md5(str).toUpperCase(); //
    return s;
}

function request(url, data = {}, method = 'GET', contentType = 'json') {
	// //console.log(url,data)
    // if (uni.getStorageSync('sjtypes') == 1) {
    //     data.token = uni.getStorageSync('sjtoken');
    // } else {
    // }
	// //console.log(uni.getStorageSync('sjtoken'))
	// //console.log(uni.getStorageSync('token'))
	data.token_shop = uni.getStorageSync('sjtoken');
	data.token = uni.getStorageSync('token');
    data.x_id = 1;
    data.pid = uni.getStorageSync('pid');
	
	// //console.log(data)
    let data3 =utilBase64.encode(JSON.stringify(data));
    data3 = addsanferewr(data3);
	
    let das = {};
    das.mx_app_key = app_keyd(host + url);
    das.tkpime = Date.parse(new Date()) / 1000;
    das.data3 = data3;
    das.api_sign = signature(das);
    // Object.keys(das).forEach(function (key) {
    //     das[key] = utilBase64.encode(das[key]);
    // });
    wx.showLoading()
    return new Promise(function (resolve, reject) {
        uni.request({
            url: host + url,
            data: das,
            method: method,
            header: {
                'Content-Type': contentType.toLowerCase() == 'json' ? 'application/json' : 'application/x-www-form-urlencoded'
                // 'token':app.globalData.token
            },

            success: function (res) {
                uni.hideLoading();
				if (res.data.code == 0){
					res.data.data=decryptAES(res.data.data.list,res.data.data.str)
					// //console.log(url,res.data)
				}
                if (res.data.code == 101) {
					uni.removeStorageSync('token');
					uni.removeStorageSync('sjtoken');
					wx.navigateTo({
					  url:"/pages/login/index"
					})
                    resolve(res.data);
                    return false;
                }
                if (res.data.code == 400) {
                    resolve(res.data);
                }
                if (res.statusCode == 200) {
                    resolve(res.data);
                } else {
                }
            },
            fail: function (err) {
                reject(err);
            }
        });
    });
}
function request1(url, data = {}, method = 'GET', contentType = 'json') {
    data.token = uni.getStorageSync('JSTOKEN');
    data.x_id = 1;
    data.pid = uni.getStorageSync('pid');
    var data3 = utilBase64.encode(JSON.stringify(data));
    //console.log(data);
    data3 = addsanferewr(data3);
    let das = {};
    das.mx_app_key = app_keyd(host + url);
    das.tkpime = Date.parse(new Date()) / 1000;
    das.data3 = data3;
    das.api_sign = signature(das);
    Object.keys(das).forEach(function (key) {
        das[key] = utilBase64.encode(das[key]);
    });
    // wx.showLoading()
    return new Promise(function (resolve, reject) {
        uni.request({
            url: hosts + url,
            data: das,
            method: method,
            header: {
                'Content-Type': contentType.toLowerCase() == 'json' ? 'application/json' : 'application/x-www-form-urlencoded'
                // 'token':app.globalData.token
            },

            success: function (res) {
                uni.hideLoading();
                //console.log(res);
                if (res.data.code == 101) {
                    if (uni.getStorageSync('fxtypes') == 1) {
                    } else {
                        // wx.clearStorageSync();
                        uni.removeStorageSync('token');
                        uni.removeStorageSync('user');
                        uni.removeStorageSync('session_key');
                        uni.removeStorageSync('token1');
                        uni.removeStorageSync('fxtypes');
                    }
                    wx.showModal({
                      title: '温馨提示',
                      content:"登录已过期,是否退出重新登录？？",
                      success: function (res) {
                          if (res.confirm) {
                              wx.clearStorageSync();
                              wx.navigateTo({
                                url:"/pages/login/index"
                              })
                          } else if (res.cancel) {
                          }
                        }
                    });
                    resolve(res.data);
                    return false;
                }
                if (res.data.code == 400) {
                    resolve(res.data);
                }
                if (res.statusCode == 200) {
                    resolve(res.data);
                } else {
                    reject(res.errMsg);
                }
            },
            fail: function (err) {
                reject(err);
            }
        });
    });
}
module.exports = {
    request: request,
    request1: request1,
	decryptAES:decryptAES
};
